package router

import (
	"net/http"
	"xframe/src/config"
	"xframe/src/core"
	"xframe/src/pkg"
	"xframe/src/pkg/common"

	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
)

func SetRouter() *gin.Engine {
	router := gin.Default()
	router.SetFuncMap(common.FuncMap()) // 设置html中模版方法

	initRouter(router)

	// 定义无匹配路由
	router.NoRoute(func(c *gin.Context) {
		c.HTML(http.StatusNotFound, "error_404", nil)
	})

	// 定义路由
	core.Router(router)

	return router
}

// 初始化路由信息
func initRouter(router *gin.Engine) {

	// 模版文件
	router.Static("/static", "public/static") // 前端依赖的资源
	router.StaticFile("/favicon.ico", "public/static/favicon.ico")
	router.LoadHTMLGlob("template/**/**/*")

	// session中间件
	router.Use(sessions.Sessions("sessionid", initSession()))
}

//初始化session
func initSession() sessions.RedisStore {
	r := config.Cfg.Redis
	conn := r.Ip + ":" + r.Port
	store, _ := sessions.NewRedisStore(10, "tcp", conn, r.Pwd, []byte("secret"))
	store.Options(sessions.Options{MaxAge: pkg.SessionLoseTime, Path: "/", HttpOnly: true})
	return store
}
